#!/usr/bin/env python

def saveWorld(world, wave, fluid, fileName="worldSave.py"):
    """A function for producing instantiation code, given a world and optionally
    a wave and a fluid."""
    file = open(fileName, "w")
    
    #Naming
    for i in range(len(world.masses)):
        world.masses[i].name = "mass" + str(i)
    for i in range(len(world.constraints)):
        world.constraints[i].name = "constraint" + str(i)
    for i in range(len(world.points)):
        world.points[i].name = "point" + str(i)
    for i in range(len(world.lines)):
        world.lines[i].name = "line" + str(i)
    
    #Writing
    endString = ")\n"
    
    file.write("from dynamics import Mass, Constraint, Point, Line\n")
    file.write("from sodalike import Clip\n\n")
    
    file.write("def loadWorld(world, wave, fluid):\n")
    
    for mass in world.masses:
        mainString = "    " + mass.name + " = Mass(world"
        posString = ", pos=(" + str(mass.x) + ", " + str(mass.y) + ")"
        weightString = ", weight=" + str(mass.weight)
        file.write(mainString + posString + weightString + endString)
    
    file.write("\n")
    
    for constraint in world.constraints:
        mainString = "    " + constraint.name + " = Constraint(world"
        m1String = ", " + str(constraint.mass1.name)
        m2String = ", " + str(constraint.mass2.name)
        lengthString = ", length=" + str(constraint.length)
        stiffnessString = ", stiffness=" + str(constraint.stiffness)
        file.write(mainString + m1String + m2String + lengthString + stiffnessString + endString)
    
    file.write("\n")
    
    for point in world.points:
        mainString = "    " + point.name + " = Point(world"
        posString = ", pos=(" + str(point.x) + ", " + str(point.y) + ")"
        file.write(mainString + posString + endString)
    
    file.write("\n")
    
    for line in world.lines:
        mainString = "    " + line.name + " = Line(world"
        p1String = ", " + str(line.p1.name)
        p2String = ", " + str(line.p2.name)
        file.write(mainString + p1String + p2String + endString)
    
    if wave != None:
        file.write("\n")
        
        for clip in wave.clips:
            mainString = "    " + clip.name + " = Clip(wave"
            constraintString = ", " + str(clip.constraint.name)
            magnitudeString = ", magnitude=" + str(clip.magnitude)
            offsetString = ", offset=" + str(clip.offset)
            file.write(mainString + constraintString + magnitudeString + offsetString + endString)
    
    if fluid != None:
        file.write("\n")
        
        for mass in fluid.masses:
            file.write("    fluid.masses.append(" + mass.name + ")\n")